package com.ifreeee.utils;

import com.ifreeee.sort.ShellSort;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

public class RandomUtils {

    /**
     * 取一个[min, max]之间的一个随机数
     * @param min
     * @param max
     * @param r 产生随机数的Random对象
     * @return
     */
    public static int randomNum(int min, int max, Random r) {
        int diff = max - min;
        if(diff < 0){//有两种情况，1）max达到Integer.MAX_VALUE 减去一个负数的 min 然后溢出 变为负数；2）min > max
            throw new RuntimeException("参数不正确min:" + min + "\tmax:" + max);
        }
        return r.nextInt(diff + 1) + min;
    }

    /**
     * 生成随机数测试
     */
    @Test
    public void test1(){
        int max = 500;
        int min = -500;
        int time = 10000000;
        int[] integers = new int[time];
        ArrayList<Integer> errIntegers = new ArrayList<>();
        for (int i = 0; i < time; i += 1){
            int i1 = RandomUtils.randomNum(min, max, new Random());
            integers[i] = i1;
            if(i1 > max || i1 < min){
                errIntegers.add(i1);
            }
        }
        ShellSort.shellSort(integers);
        System.out.println(Arrays.toString(integers));
        for(int value : errIntegers){
            System.out.println("错误数据" + value);
        }
    }
}
